<template>
  <div class="company-detail">
    <!-- 企业名称搜索区域，与 SearchResult.vue 统一 -->
    <div class="company-search-container">
      <el-input v-model="searchForm.companyName" clearable placeholder="请输入企业名称、经营范围等关键词"
        @keyup.enter.native="handleCompanySearch" style="width: 1029px;">
        <template #prefix>
          <el-icon style="color: #383838; margin-right: 5px;">
            <Search />
          </el-icon>
        </template>
        <template #append>
          <el-button type="primary" @click="handleCompanySearch" class="custom-search-btn">
            查询一下
          </el-button>
        </template>
      </el-input>
    </div>
    <div>
      <!-- 基础信息 -->
      <div class="company-info" style="width: 1500px; margin: 0 auto;">
        <div class="company-logo" :style="{ backgroundColor: randomBgColor }">
          <!-- {{ selectedCompany.keywords }} -->
          <span>
            {{ (selectedCompany.alias && selectedCompany.alias.length > 2)
              ? selectedCompany.alias.slice(0, 2) + '\n' + selectedCompany.alias.slice(2)
              : (selectedCompany.alias || '--') }}
          </span>
        </div>
        <div class="company-details">
          <div class="info-item" style="overflow: hidden;">
            <span class="name" style="float: left;" v-html="highlightedName"></span>
            <span class="status" style="float: left;padding-top: 3px;" v-if="selectedCompany.regStatus">{{
              selectedCompany.regStatus ?
                selectedCompany.regStatus :
                '--' }}</span>
          </div>
          <el-tag v-for="item in listdata" type="warning" style="margin-right: 23px;margin-bottom: 10px;"
            color="#FFF0E0" effect="plain">
            {{ item }}
          </el-tag>
          <div class="deta_bot">

            <div class="info-item">
              <span class="label">统一社会信用代码：</span>
              <span class="value">{{ selectedCompany.creditCode }}</span>
            </div>
            <div class="info-item">
              <span class="label">法定代表人：</span>
              <span class="value">{{ selectedCompany.legalPersonName }}</span>
            </div>
            <div class="info-item">
              <span class="label">注册资本：</span>
              <span class="value">
                {{
                  (selectedCompany.regCapital || '')
                }}
              </span>
            </div>
            <div class="info-item">
              <span class="label">成立日期：</span>
              <span class="value">{{ formatTimestamp(selectedCompany.estiblishTime) || '--' }}</span>
            </div>
            <div class="info-item">
              <span class="label">地址：</span>
              <el-tooltip :content="selectedCompany.regLocation || '--'" placement="top">
                <span class="value">{{ selectedCompany.regLocation || '--' }}</span>
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>

    </div>
    <!-- 自定义选项卡 -->
    <div class="custom-tabs" style="width: 1600px; margin:35px auto;  ">
      <div style="display: flex;">
        <div v-for="(tab, index) in tabs" :key="index" :class="{ 'active': activeTab === index }"
          @click="activeTab = index">
          {{ tab }}
        </div>
      </div>

    </div>
    <!-- 根据选中的选项卡展示不同内容 -->
    <div v-if="selectedCompany" class="company-info" style="width: 1534.88px;">
      <div v-if="activeTab === 0">
        <div class="biaog">
          <div class="b_top">
            <div class="bt_left">
              <div class="info-item">
                <div class="label name">
                  企业法人
                </div>
                <span class="value name">{{ selectedCompany.legalPersonName || '--' }}</span>
              </div>
              <div class="info-item">
                <div class="label ">
                  公司类型
                </div>
                <span class="value">{{ selectedCompany.companyOrgType || '--' }}</span>
              </div>
              <div class="info-item">
                <div class="label ">
                  经营状态
                </div>
                <span class="value">{{ selectedCompany.regStatus || '--' }}</span>
              </div>
              <div class="info-item">
                <div class="label ">
                  注册资本
                </div>
                <span class="value">
                  {{
                    (selectedCompany.regCapital || '--')
                  }}
                </span>
              </div>
              <div class="info-item">
                <div class="label ">
                  成立日期
                </div>
                <span class="value">{{ formatTimestamp(selectedCompany.estiblishTime) || '--' }}</span>
              </div>
              <div class="info-item">
                <div class="label ">
                  登记机关
                </div>
                <span class="value">{{ selectedCompany.regInstitute || '--' }}</span>
              </div>
              <div class="info-item">
                <div class="label">
                  公司规模
                </div>
                <span class="value">{{ selectedCompany.staffNumRange || '--' }}</span>
              </div>
              <div class="info-item">
                <div class="label ">
                  所属行业
                </div>
                <el-tooltip
                  :content="selectedCompany.industryCategory + (selectedCompany.industryCategoryMiddle ? '>' + selectedCompany.industryCategoryMiddle : '') + (selectedCompany.industryCategorySmall ? '>' + selectedCompany.industryCategorySmall : '')"
                  placement="top">
                  <span class="value">{{
                    selectedCompany.industryCategory + (selectedCompany.industryCategoryMiddle ? '>' +
                      selectedCompany.industryCategoryMiddle : '') + (selectedCompany.industryCategorySmall ? '>' +
                        selectedCompany.industryCategorySmall : '')
                  }}</span>
                </el-tooltip>
              </div>
            </div>
            <div class="bt_right">
              <div class="info-item">
                <div class="label ">
                  统一社会信用代码
                </div>
                <span class="value">{{ selectedCompany.creditCode || '--' }}</span>
              </div>
              <div class="info-item">
                <div class="label ">
                  组织机构代码
                </div>
                <span class="value">{{ selectedCompany.orgNumber || '--' }}</span>
              </div>
              <div class="info-item">
                <div class="label ">
                  注册号
                </div>
                <span class="value">{{ selectedCompany.regNumber || '--' }}</span>
              </div>
              <div class="info-item">
                <div class="label ">
                  营业期限
                </div>
                <span class="value">{{ formatTimestamp(selectedCompany.fromTime) + '至'
                  + (formatTimestamp(selectedCompany.toTime) == '--' ? '永续经营' : (selectedCompany.toTime ?
                    formatTimestamp(selectedCompany.toTime) : '无固定期限')) }}</span>
              </div>
              <div class="info-item">
                <div class="label ">
                  实缴资本
                </div>
                <span class="value">{{ selectedCompany.actualCapital || '--' }}</span>
              </div>
              <div class="info-item">
                <div class="label ">
                  核准日期
                </div>
                <span class="value">{{ formatTimestamp(selectedCompany.approvedTime) }}</span>
              </div>
              <div class="info-item">
                <div class="label ">
                  曾用名
                </div>
                <span class="value">{{ selectedCompany.historyNames || '--' }}</span>
              </div>
              <div class="info-item">
                <div class="label ">
                  参保人数
                </div>
                <span class="value">{{ selectedCompany.socialStaffNum || '--' }}</span>
              </div>
              <div class="info-item">
                <div class="label ">
                  英文名称
                </div>
                <span class="value">{{ selectedCompany.property3 || '--' }}</span>
              </div>
            </div>
          </div>
          <div class="b_bot">
            <div class="info-item">
              <div class="label ">
                企业地址
              </div>
              <span class="value">{{ selectedCompany.regLocation || '--' }}</span>
            </div>
            <div class="info-item">
              <div class="label ">
                经营范围
              </div>
              <span class="value" style="min-height: 57px;
    overflow-y: auto;
    white-space: normal;
    line-height: 1.5;
    padding: 5px 0px;
    padding-left: 26px;
    display: flex;
    justify-content: left;
    align-items: center;">{{ selectedCompany.businessScope || '--' }}</span>
            </div>
          </div>
        </div>
      </div>
      <div v-if="activeTab === 1" style="width: 100%;">
        <!-- 竞争公司数据 -->
        <el-table :data="supplier" v-if="supplier.length != 0" border style="width: 100%">
          <el-table-column type="index" label="序号" align="center" width="100">
          </el-table-column>
          <el-table-column prop="supplierName" label="供应商" align="center">
            <template #default="scope">
              <div style="display: flex; align-items: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                <img :src="scope.row.logoUrl" alt="供应商Logo" v-if="scope.row.logoUrl"
                  style="width: 30px; height: 30px; margin-right: 10px;">
                <div style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{ scope.row.supplierName || "--" }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="purchaseRatio" label="采购占比" align="center">
            <template #default="scope">
              {{ scope.row.purchaseRatio || "--" }}
            </template>
          </el-table-column>
          <el-table-column prop="purchaseAmount" label="采购金额" align="center">
            <template #default="scope">
              {{ scope.row.purchaseAmount || "--" }}
            </template>
          </el-table-column>
          <el-table-column prop="announcementDate" align="center" label="报告期">
            <template #default="scope">
              {{ formatTimestamp(scope.row.announcementDate) }}
            </template>
          </el-table-column>
          <el-table-column label="数据来源" align="center">
            <template #default="scope">
              <!--              <router-link :to="`/supplier/detail/${scope.row.id}`" class="supplier-link">
                招投标公告
              </router-link>-->
              <div class="supplier-link" style="color:#8c8c8c">
                招投标公告
              </div>
            </template>

          </el-table-column>
        </el-table>
        <div class="kong" v-if="supplier.length == 0">
          <img src="@/assets/images/kong.png" alt="">
          暂无供应商数据
        </div>
      </div>
      <div class="timeline" style="width: 100%;" v-if="activeTab === 3">
        <!-- 采购意向 -->
        <PurchaseIntent :data="purchaseIntents" />
        <div class="kong" v-if="purchaseIntents.length == 0">
          <img src="@/assets/images/kong.png" alt="">
          暂无采购意向
        </div>
      </div>
      <div style="width: 100%;" v-if="activeTab === 4">
        <!-- 联系人信息 -->
        <ContactInfo :data="selectedCompanys" :company-name="selectedCompany.name" />
        <div class="kong" v-if="selectedCompanys.length == 0">
          <img src="@/assets/images/kong.png" alt="">
          暂无联系人信息
        </div>
      </div>
        <div style="width: 100%;" v-if="activeTab === 2">
          <Tendering></Tendering>

      </div>

    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, onActivated } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import baseService from "@/service/baseService";
import PurchaseIntent from './components/PurchaseIntent.vue';
// 引入公司信息列表数据
import { companyInfoList } from './constants/listData';
import { ElMessage } from 'element-plus';
const router = useRouter();
// 引入联系人信息组件
import ContactInfo from './components/ContactInfo.vue';
import Tendering from './components/tendering/index.vue';
// 获取当前路由实例
const route = useRoute();
const currentPage = ref(1); // 当前页码
const pageSize = ref(100);   // 每页条数
const total = ref(0);       // 总数据量
// 搜索表单
const searchForm = reactive({
  companyName: ''
});
const id = ref('');
// 定义选项卡列表
const tabs = ref(['基础信息', '供应商数据','招投标信息' , '采购意向', '联系人信息']);
// 定义当前选中的选项卡索引
const activeTab = ref(0);
const listdata = ref([]);
const purchaseIntents = ref([]);
const selectedCompanys = ref({});
const supplier = ref([]);
// 选中的公司信息
const selectedCompany = ref({
});

// 定义随机背景颜色的 ref
const randomBgColor = ref('');

// 定义固定颜色数组
const fixedColors = [
  '#13D7C6', '#0594FF', '#5733FF', '#FFC300', '#33A6FF', '#FFD733'
];

// 生成随机颜色的函数，从固定颜色中随机选取
const getRandomColor = () => {
  const randomIndex = Math.floor(Math.random() * fixedColors.length);
  return fixedColors[randomIndex];
};

// 时间戳转换为 YYYY-MM-DD 格式日期的方法，增加空值判断
const formatTimestamp = (timestamp: number | string | null | undefined): string => {
  if (!timestamp) {
    return '暂无数据';
  }
  const date = new Date(Number(timestamp));
  if (isNaN(date.getTime())) {
    return '暂无数据';
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
const handleCompanyData = () => {
  //获取基本信息
  baseService.get('/noc/companybasicinfo/info/' + id.value, {}).then((res) => {
    if (res.code == 0) {
      //刷新
      selectedCompany.value = res.companyBasicInfo;
    }
  })
  //展会信息
  baseService.get('/noc/companybasicinfo/getExhibitionName/' + id.value, {}).then((res) => {
    if (res.code == 0) {
      //刷新
      listdata.value = res.exhibitionNames;
    }
  })
  //竞争公司数据
  baseService.get('/noc/companysupplierinfo/list?id=' + id.value + '&page=' + currentPage.value + '&limit=' + pageSize.value, {}).then((res) => {
    if (res.code == 0) {
      //刷新
      supplier.value = res.page.list;
      total.value = res.page.totalCount;
    }
  })
  //采购意向
  baseService.get('/noc/companybasicinfo/getPurchaseIntention/' + id.value, {}).then((res) => {
    if (res.code == 0) {
      //刷新
      purchaseIntents.value = res.list;
    }
  })
  //联系人信息
  baseService.get('/noc/companyemployee/list?id=' + id.value + '&page=1&limit=999999', {}).then((res) => {
    if (res.code == 0) {
      //刷新
      selectedCompanys.value = res.page.list;
    }
  })
}
// 分页事件处理
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  handleCompanyData(); // 切换页码时重新获取数据
};

// 处理企业名称搜索
const handleCompanySearch = () => {
  if (searchForm.companyName == '') return ElMessage({
    message: '请输入搜索关键词',
    type: 'warning',
  });
  ;
  router.push({
    path: '/search-result',
    query: {
      name: searchForm.companyName
    }
  })
};
// 新增：处理名称高亮逻辑
const highlightedName = computed(() => {
  const name = selectedCompany.value.name || '暂无数据';
  const keyword = route.query.name
  // 关键词为空时直接返回原名称
  if (!keyword) return name;

  // 正则匹配关键词（忽略大小写），用<span>包裹匹配部分
  const regex = new RegExp(`(${escapeRegExp(keyword)})`, 'gi');
  return name.replace(regex, '<span class="highlight" style="color: rgba(255, 46, 46, 1);">$1</span>');
});

// 辅助函数：转义正则特殊字符
const escapeRegExp = (str: string) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
onMounted(() => {
  // 获取路由参数，假设参数名为 companyName
  const companyNameFromRoute = route.query.id as string;
  const nameFromRoute = route.query.name as string;
  if (companyNameFromRoute) {
    id.value = companyNameFromRoute;
    handleCompanyData();
  }
  if (nameFromRoute) {
    searchForm.companyName = nameFromRoute;
  }
  randomBgColor.value = getRandomColor();
});
// 页面显示时执行（路由切换返回时触发）
onActivated(() => {
  // 获取路由参数，假设参数名为 companyName
  const companyNameFromRoute = route.query.id as string;
  const nameFromRoute = route.query.name as string;
  if (companyNameFromRoute) {
    id.value = companyNameFromRoute;
    handleCompanyData();
  }
  if (nameFromRoute) {
    searchForm.companyName = nameFromRoute;
  }
  randomBgColor.value = getRandomColor();
});
</script>

<style scoped lang="less">
.company-details {
  flex: 1;
  &.highlight{
            color: rgba(255, 46, 46, 1);
            padding-right: 20px;
        }
}

.company-search-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.company-logo {
  width: 83px;
  height: 83px;
  line-height: 83px;
  border-radius: 15px;
  display: flex;
  color: #fff;
  font-size: 20px;
  justify-content: center;
  align-items: center;
}
.company-logo span {
  white-space: pre-line;
  line-height: 25px;
}
.custom-tabs {
  display: flex;
  background: rgba(239, 244, 255, 1);
  margin-top: 18px;
  font-size: 16px;
  margin-bottom: 36px;
  width: 100% !important;
}

.custom-tabs div {
  padding: 0 22px;
  margin: 0 20px;
  cursor: pointer;
  line-height: 40px;
  transition: background-color 0.3s;
}

.custom-tabs div.active {
  background-color: #fff;
  border-top: 1px solid #1677FF;
  color: #1677FF;
  line-height: 40px;
}

.company-info {
  display: flex;
  gap: 41px;
  font-family: "Microsoft YaHei";
  // width: 1400px;
  width: 100% !important;
  margin: 0 auto;
  /* 移除 el-tag 边框 */
  ::v-deep .no-border-tag {
    border: none !important;
  }
}

.info-item {
  margin-bottom: 10px;
}

.label {
  margin-right: 10px;
}

.name {
  color: rgba(0, 0, 0, 1);
  font-size: 24px;
}

.status {
  border-radius: 5px;
  background: #eff4ff;
  color: rgba(16, 98, 202, 1);
  line-height: 23px;
  margin-left: 21px;
  font-size: 16px;
  width: 61px;
  text-align: center;
  display: inline-block;
  border: 1px solid rgba(16, 98, 202, 1);
}

.value {
  color: #333;
}

.deta_bot {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  padding-top: 13px;

}

.deta_bot .info-item {
  width: 32%;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 16px;
  color: rgba(56, 56, 56, 1);
  white-space: nowrap;
}
.kong{
  // padding-top: 174px;
  width: 447px;
  margin: 0 auto;
  font-size: 18px;
  text-align: center;
  span{
    color: rgba(22, 119, 255, 1);
  }
  img{
    width: 250px;
    display: block;
    margin: 0 auto;
    // height: 280px;
  }
}
.deta_bot .info-item .value {
  max-width: calc(100% - 100px);
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: top;
}

.biaog {
  border: 1px solid #C7C7C7;
  // width: 1534.88px;
  width: 100% !important;

  .b_top {
    border-bottom: 1px solid #C7C7C7;
    overflow: hidden;
    
    
    .bt_left,
    .bt_right {
      width: 50%;
      border-right: 1px solid #C7C7C7;
      float: left;

      .label {
        width: 184px;
        // width: 20%;
      }

      .value {
        white-space: nowrap;
        overflow: hidden;         /* 隐藏溢出内容 */
        text-overflow: ellipsis;  /* 显示省略号 */
        padding-right:20px;
      }

      .info-item:last-child {
        border-bottom: none;
      }
    }
    .bt_right {
      border-right: none;
    }
  }

  .b_bot {
    .label {
      // width: 209px;
      // width: 10%;
      width: 184px;
    }

    .value {
      // width: 90%;
    }

    .info-item:last-child {
      border-bottom: none;
    }
  }

  .info-item {
    /* 使用 flex 布局确保 label 和 value 垂直对齐 */
    display: flex;
    align-items: center;
    /* 垂直居中对齐 */
    min-height: 57px;
    /* 固定行高，与 line-height 保持一致 */
    margin-bottom: 0;
    background: #EFF4FF;
    /* 确保背景色生效 */
    border-bottom: 1px solid #C7C7C7;
  }

  .label {
    color: #000000;
    font-size: 16px;
    height: 100%;
    text-align: center;
    margin-right: 0;
    /* 添加：使用 flex 布局使文本垂直居中 */
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .value {
    color: #383838;
    font-size: 16px;
    padding-left: 26px;
    border-left: 1px solid #C7C7C7;
    // 添加不换行和滚动条样式

    // width: 584px;
    width: calc(100% - 184px);
    background: #fff;
    /* 确保背景色生效 */
    line-height: 57px;
    border-left: 1px solid #C7C7C7;
  }

  .name.value {
    color: rgba(56, 56, 56, 1);
    font-size: 24px;
  }

  .name {
    line-height: 116px;
  }
}

/* 自定义按钮样式 */
.custom-search-btn {
  width: 106px;
  height: 35px;
  border-radius: 3px;
  background: #FF9833;
  font-size: 16px;
  color: #fff !important;
  text-align: center;

  &.el-button--primary {
    background-color: #FF9833;
    border-color: #FF9833;

    &:hover,
    &:focus {
      background: lighten(#FF9833, 10%);
      border-color: lighten(#FF9833, 10%);
    }
  }
}
</style>

